using System;
using System.Collections.Generic;
using System.Windows.Forms;

using Elev.Core;
using Elev.UI.Controls;

namespace Elev.UI
{
    public class GetPeriodsCommand : ICommand
    {
        GetPeriodsCommandDelegate invokeMe;
        IPeriodListsManager periodsList;

        // Delegate used to retreive tags asynchronously
        delegate List<Period> GetPeriodsCommandDelegate();

        public GetPeriodsCommand(IPeriodListsManager List)
        {
            periodsList = List;

            PeriodsFactory factory = new PeriodsFactory();
            invokeMe = new GetPeriodsCommandDelegate(factory.GetPeriods);
        }

        void Callback(IAsyncResult ar)
        {
            // get the dataset as output
            List<Period> periods = new List<Period>();
            try
            {
                periods = invokeMe.EndInvoke(ar);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // update the grid a thread safe fasion!
            MethodInvoker updateList = delegate
            {
                try
                {
                    periodsList.Clear();
                    periodsList.Loading = true;

                    foreach (Period period in periods)
                        periodsList.Add(period);

                    // Select the grid of the selected period tab
                    int intialSelectedPeriod = MetaInfo.SelectedPeriod;
                    if (intialSelectedPeriod < periodsList.Count)
                        periodsList.SelectPeriod(intialSelectedPeriod);
                    else
                        periodsList.SelectPeriod(0);                    
                    
                    periodsList.Loading = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            };

            if (periodsList.InvokeRequired)
            {
                periodsList.Invoke(updateList);
            }
            else
            {
                updateList();
            }
        }

        #region ICommand Members

        public void Execute()
        {
            invokeMe.BeginInvoke(this.Callback, null);
        }

        #endregion
    }
}
